package com.work.yshop.ui.activity;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.work.yshop.R;
import com.work.yshop.adapter.ProductAdapter;
import com.work.yshop.model.Product;
import com.work.yshop.utils.UserSession;

import java.util.ArrayList;
import java.util.List;

/**
 * 商品列表页面 - 显示卖家的商品
 */
public class ProductListActivity extends AppCompatActivity {

    private Toolbar toolbar;
    private RecyclerView recyclerView;
    private ProductAdapter adapter;
    private View emptyView;
    private FloatingActionButton fabAdd;
    private List<Product> products;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_product_list);
        
        initViews();
        setupToolbar();
        setupListeners();
        loadProducts();
    }
    
    @Override
    protected void onResume() {
        super.onResume();
        // 重新加载数据，以便在添加或编辑商品后刷新列表
        loadProducts();
    }
    
    private void initViews() {
        toolbar = findViewById(R.id.toolbar);
        recyclerView = findViewById(R.id.recycler_view);
        emptyView = findViewById(R.id.empty_view);
        fabAdd = findViewById(R.id.fab_add);
        
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        adapter = new ProductAdapter();
        recyclerView.setAdapter(adapter);
    }
    
    private void setupToolbar() {
        setSupportActionBar(toolbar);
        if (getSupportActionBar() != null) {
            getSupportActionBar().setTitle("我的货品");
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
            getSupportActionBar().setDisplayShowHomeEnabled(true);
        }
        
        toolbar.setNavigationOnClickListener(v -> onBackPressed());
    }
    
    private void setupListeners() {
        // 设置点击商品项的监听器
        adapter.setOnItemClickListener(position -> {
            Product product = adapter.getItem(position);
            if (product != null) {
                // 打开商品详情页
                Toast.makeText(this, "查看商品: " + product.getName(), Toast.LENGTH_SHORT).show();
                // 可以添加打开商品详情页的代码
                // Intent intent = new Intent(this, ProductDetailActivity.class);
                // intent.putExtra("product_id", product.getId());
                // startActivity(intent);
            }
        });
        
        // 设置编辑按钮的监听器
        adapter.setOnEditClickListener(position -> {
            Product product = adapter.getItem(position);
            if (product != null) {
                // 打开编辑商品页面
                Intent intent = new Intent(this, ProductAddActivity.class);
                intent.putExtra("product", product);
                intent.putExtra("is_edit", true);
                startActivity(intent);
            }
        });
        
        // 设置上下架按钮的监听器
        adapter.setOnToggleStatusClickListener(position -> {
            Product product = adapter.getItem(position);
            if (product != null) {
                toggleProductStatus(product, position);
            }
        });
        
        // 设置添加商品按钮的监听器
        fabAdd.setOnClickListener(v -> {
            // 打开添加商品页面
            Intent intent = new Intent(this, ProductAddActivity.class);
            startActivity(intent);
        });
        
        // 设置空视图中的添加按钮监听器
        findViewById(R.id.btn_add_product).setOnClickListener(v -> {
            // 打开添加商品页面
            Intent intent = new Intent(this, ProductAddActivity.class);
            startActivity(intent);
        });
    }
    
    // 切换商品状态（上架/下架）
    private void toggleProductStatus(Product product, int position) {
        int newStatus = product.getStatus() == 1 ? 0 : 1;
        String statusText = newStatus == 1 ? "上架" : "下架";
        
        // 弹出确认对话框
        new AlertDialog.Builder(this)
                .setTitle("确认" + statusText)
                .setMessage("确定要" + statusText + "商品 \" + product.getName() + \" 吗？")
                .setPositiveButton("确定", (dialog, which) -> {
                    // 更新商品状态
                    product.setStatus(newStatus);
                    updateProductStatus(product, position);
                })
                .setNegativeButton("取消", null)
                .show();
    }
    
    // 更新商品状态
    private void updateProductStatus(Product product, int position) {
        // 这里应该调用API更新商品状态
        // 模拟API调用成功
        String statusText = product.getStatus() == 1 ? "上架" : "下架";
        Toast.makeText(this, "商品已" + statusText, Toast.LENGTH_SHORT).show();
        
        // 更新列表
        products.set(position, product);
        adapter.setData(products);
    }
    
    private void loadProducts() {
        // 模拟加载卖家的商品数据
        products = new ArrayList<>();
        
        // 获取当前卖家ID
        int sellerId = UserSession.getInstance().getUserId();
        
        // 添加模拟数据
        products.add(new Product(1, "有机红富士苹果", "新鲜采摘，无农药残留", 15.8, "https://via.placeholder.com/100", 4.8f, 258));
        products.add(new Product(2, "农家土鸡蛋", "散养土鸡下的蛋，营养丰富", 3.5, "https://via.placeholder.com/100", 4.9f, 186));
        products.add(new Product(3, "有机胡萝卜", "富含胡萝卜素，新鲜采摘", 2.5, "https://via.placeholder.com/100", 4.7f, 120));
        products.add(new Product(4, "新鲜西红柿", "自家种植，绿色无公害", 4.5, "https://via.placeholder.com/100", 4.6f, 95));
        products.add(new Product(5, "黄瓜", "农家种植，新鲜可口", 2.8, "https://via.placeholder.com/100", 4.5f, 78));
        
        // 设置状态
        for (int i = 0; i < products.size(); i++) {
            products.get(i).setStatus(i % 2 == 0 ? 1 : 0); // 模拟部分商品已下架
            products.get(i).setStock(100 + i * 20); // 设置库存
        }
        
        if (products.isEmpty()) {
            recyclerView.setVisibility(View.GONE);
            emptyView.setVisibility(View.VISIBLE);
        } else {
            recyclerView.setVisibility(View.VISIBLE);
            emptyView.setVisibility(View.GONE);
            adapter.setData(products);
        }
    }
} 